/**
 * 
 */
package com.auz.datagenerator.heuristics.time;

import java.util.logging.Logger;

import javax.swing.JPanel;

import com.auz.datagenerator.connector.IConnector;
import com.auz.datagenerator.heuristics.time.gui.SetIntervalHeuristicPanel;

/**
 * @author Aurelien Bonnel
 * Class used to send notifications to the connector at a set interval (defined in milliseconds).
 * When this class is created and the thread launched, it will exist until a call to halt is issued. 
 */
public class SetIntervalHeuristic extends Thread implements IIntervalHeuristic {

	Logger logger = Logger.getLogger("SetIntervalHeuristic");
	
	private int interval;
	private boolean sending = false, running = true;
	private IConnector connector;
	
	/**
	 * Constructor
	 * @param _interval - the interval in milliseconds
	 * @param _connector - the attached connector receiving triggering events
	 */
	public SetIntervalHeuristic(int _interval, IConnector _connector) {
		interval = _interval;
		connector = _connector;
	}
	
	/**
	 * Sets the interval to the specified value
	 * @param _interval - the new interval in milliseconds
	 */
	public SetIntervalHeuristic(int _interval) {
		interval = _interval;
	}
	
	/**
	 * Runs the interval heuristic in a separate thread
	 */
	public void run() {
		logger.info("SetIntervalHeuristic with interval " + interval + " started");
		while(running) {
			try {
				sleep(interval);
				if(sending) {
					connector.trigger();
				}
			} catch (InterruptedException e) {
				logger.severe("SetIntervalHeuristic with interval " + interval + " interrupted");
			}
		}
	}
	
	/**
	 * Unpause the interval heuristic 
	 */
	public void unpause() {
		logger.finest("SetIntervalHeuristic with interval " + interval + " resumed");
		sending = true;
	}
	
	/**
	 * Completely halts the interval heuristic
	 */
	public void halt() {
		logger.info("SetIntervalHeuristic with interval " + interval + " halted");
		running = false;
	}

	/**
	 * Pause the interval heuristic
	 */
	public void pause() {
		logger.finest("SetIntervalHeuristic with interval " + interval + " paused");
		sending = false;
	}
	
	/**
	 * Sets the associated connector as specified
	 * @param _connector - the new connector
	 */
	public void setConnector(IConnector _connector) {
		connector = _connector;
	}
	
	/**
	 * Fetches the associated GUI component
	 * @return a JPanel associated with this timer
	 */
	public JPanel fetchGUIComponent() {
		return new SetIntervalHeuristicPanel(this);
	}

	/**
	 * Gets the interval
	 * @return the interval
	 */
	public int getInterval() {
		return interval;
	}
	
	/**
	 * Sets the interval to be as specified 
	 * @param _interval - the new interval
	 */
	public void setInterval(int _interval) {
		if(_interval == 0)
			pause();
		else {
			interval = _interval;
			this.interrupt();
		}
	}
	
}
